package com.tools;

import android.graphics.Bitmap;
import android.opengl.GLES32;
import android.opengl.GLUtils;

import com.system.FileUtils;

/**
 * @Author: clm
 * @Date: 2018-10-29
 */

public class TextureTools {
    public final static int genSimplerTexture(int textureTag, String filename){
        Bitmap img = FileUtils.getFromAssetsAtBitmap(filename);
        int[] mTex2Ds = genSimplerTextureAtBitmap(textureTag, img);
        return mTex2Ds[0];
    }

    public static int[] genSimplerTextureAtBitmap(int textureTag, Bitmap img) {
        int []mTex2Ds = new int[1];
        GLES32.glGenTextures(1, mTex2Ds, 0);
        GLES32.glBindTexture(textureTag, mTex2Ds[0]);
        GLUtils.texImage2D(textureTag, 0, img, GLES32.GL_FALSE);
        //纹理过滤
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_MAG_FILTER, GLES32.GL_LINEAR);             //近处时的过滤方式(即物体变大时)
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_MIN_FILTER, GLES32.GL_NEAREST);             //远处时的过滤方式(即物体变小时)
        //纹理重复模式
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_S, GLES32.GL_CLAMP_TO_EDGE);
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_T, GLES32.GL_CLAMP_TO_EDGE);
        GLES32.glGenerateMipmap(textureTag);
        img.recycle();//销毁
        GLES32.glBindTexture(textureTag, 0);
        return mTex2Ds;
    }

    /**
     * 创建一个指定位图的纹理,但不销毁该位图
     * @param textureTag
     * @param img
     * @return
     */
    public static int[] genSimplerTextureAtBitmapNotRecycler(int textureTag, Bitmap img) {
        int []mTex2Ds = new int[1];
        GLES32.glGenTextures(1, mTex2Ds, 0);
        GLES32.glBindTexture(textureTag, mTex2Ds[0]);
        GLUtils.texImage2D(textureTag, 0, img, GLES32.GL_FALSE);
        //纹理过滤
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_MAG_FILTER, GLES32.GL_LINEAR);             //近处时的过滤方式(即物体变大时)
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_MIN_FILTER, GLES32.GL_NEAREST);             //远处时的过滤方式(即物体变小时)
        //纹理重复模式
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_S, GLES32.GL_CLAMP_TO_EDGE);
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_T, GLES32.GL_CLAMP_TO_EDGE);
        GLES32.glGenerateMipmap(textureTag);
        GLES32.glBindTexture(textureTag, 0);
        return mTex2Ds;
    }

    public final static int genSimplerTextureAtWrapRepeat(int textureTag, String filename){
        Bitmap img = FileUtils.getFromAssetsAtBitmap(filename);
        int[] mTex2Ds = genSimplerTextureAtBitmap(textureTag, img);
        GLES32.glBindTexture(textureTag, mTex2Ds[0]);
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_S, GLES32.GL_REPEAT);
        GLES32.glTexParameteri(textureTag, GLES32.GL_TEXTURE_WRAP_T, GLES32.GL_REPEAT);
        GLES32.glBindTexture(textureTag, 0);
        return mTex2Ds[0];
    }
}
